/**
 * Copyright (c) 2016-2019 九点科技 All rights reserved.
 *
 * http://www.9dyun.cn
 *
 * 版权所有，侵权必究！
 */
package com.dian.modules.inv.service.impl;

import com.dian.common.exception.RRException;
import com.dian.common.utils.*;
import com.dian.common.validator.ValidatorUtils;
import com.dian.common.validator.group.AddGroup;
import com.dian.common.validator.group.UpdateGroup;
import com.dian.modules.base.service.BaseConfigService;
import com.dian.modules.inv.entity.InHeadEntity;
import com.dian.modules.inv.vo.GoodsStockVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.collections.CollectionUtils;
import cn.hutool.core.util.StrUtil;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import com.dian.common.server.CommonService;
import com.dian.modules.inv.dao.GoodsAccountDao;
import com.dian.modules.inv.entity.GoodsAccountEntity;
import com.dian.modules.inv.service.GoodsAccountService;
import com.dian.modules.inv.poi.vo.GoodsAccountExportVO;

/**
 * 月结报表服务实现类
 *
 * @author xiaolai
 * @email xiaolai@9dyun.cn
 * @date 2019-06-27 11:48:04
 */
@Service("goodsAccountService")
public class GoodsAccountServiceImpl extends ServiceImpl<GoodsAccountDao, GoodsAccountEntity> implements GoodsAccountService {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    public CommonService commonService;

    @Autowired
    public BaseConfigService baseConfigService;


    /**
     * 月结报表分页
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        IPage<GoodsAccountEntity> page = this.page(new Query<GoodsAccountEntity>().getPage(params),getQueryWrapper(params) );
        return new PageUtils(page);
    }

    /**
     *  月结报表新增
     * @param goodsAccountEntity
     * @return
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean saveInfo(GoodsAccountEntity goodsAccountEntity) {

        //设置编码，等基础默然初始化数据设置
        //数据完整性校验
        this.paramsCheck(goodsAccountEntity,AddGroup.class);

        //保存
        this.save(goodsAccountEntity);

        return true;
    }

    /**
     *月结报表更新
     * @param goodsAccountEntity
     * @return
     */
    @Override
    public boolean updateInfo(GoodsAccountEntity goodsAccountEntity) {

        //修改状态校验
        this.updateCheck(goodsAccountEntity.getId());

        //主表数据完整性校验
        this.paramsCheck(goodsAccountEntity, UpdateGroup.class);

        //更新主表
        this.updateById(goodsAccountEntity);


        return true;
    }

    /**
     *月结报表删除
     * @param ids
     * @return
     */
    @Override
    public boolean deleteInfo(Long[] ids) {

        //删除状态校验
        this.deleteCheck(ids);

        //更新主表
        this.remove(new QueryWrapper<GoodsAccountEntity>().in("id",ids));

        return true;
    }

    /**
     * 月结报表详情
     * @param id
     * @return
     */
    @Override
    public GoodsAccountEntity getInfo(Long id) {
        GoodsAccountEntity goodsAccountEntity =getById(id);
        return goodsAccountEntity;
    }

    /**
     * 月结报表审核
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean checkInfo(Long id) {
        GoodsAccountEntity goodsAccountEntity =this.getById(id);
        checkCheck(goodsAccountEntity);
        //goodsAccountEntity.setOrderState(OrderHead_OrderStateEnum.AUDITED.getValue());
        //goodsAccountEntity.setOrderDate(new Date());
        ///goodsAccountEntity.setCheckUserId(commonService.getUserId());
        //goodsAccountEntity.setCheckUserName(commonService.getUserName());
        return this.updateById(goodsAccountEntity);
    }


    /**
     *月结报表当前页or全部导出
     * @param params
     * @return
     */
    @Override
    public List<GoodsAccountExportVO> exportList(Map<String, Object> params) {
        List<GoodsAccountEntity> list;
        if(!StrUtil.isBlankIfStr(params.get("exprotType"))){
            list= this.page(new Query<GoodsAccountEntity>().getPage(params),getQueryWrapper(params)).getRecords();
        }else{
            list= this.list(getQueryWrapper(params));
        }

        List<GoodsAccountExportVO> resultList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(list)) {
            resultList = BeanConverter.convertList(list, GoodsAccountExportVO.class);
        }
        return resultList;
    }

    @Override
    public boolean initBeginAccount( GoodsAccountEntity goodsAccountEntity) {
        goodsAccountEntity.setAccountDate(new Date());
        this.saveOrUpdate(goodsAccountEntity);
        return false;
    }

    /**
     * 仓库月结查询
     * @param params
     * @return
     */
    @Override
    public PageUtils warehouseList(Map<String, Object> params){
        IPage<GoodsAccountEntity> page = this.page(new Query<GoodsAccountEntity>().getPage(params),
                getQueryWrapper(params) );
        return new PageUtils(page);
    }


    /**
     * 查询商品的期初数量
     * @param goodsStockVO
     * @return
     */
    @Override
    public GoodsAccountEntity queryGoodsBeginAccount(GoodsStockVO goodsStockVO) {
        //检查参数是否完整
        ValidatorUtils.validateEntity(goodsStockVO, AddGroup.class);
        String settleMonth=baseConfigService.getValue("SettleMonth");
        if(StrUtil.isBlank(settleMonth)){
            throw new RRException(String.format("系统结算月份未初始化"));
        }

        QueryWrapper<GoodsAccountEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("tenant_id",commonService.getTenantId());
        queryWrapper.eq("account_month",settleMonth);
        queryWrapper.eq("goods_id",goodsStockVO.getGoodsId());
        queryWrapper.eq("warehouse_id",goodsStockVO.getWarehouseId());

        // TODO: 2019/7/8 账务表增加索引,确保唯一性
        return this.getOne(queryWrapper);
    }




    /***********************************************************************************************/
    /****************************************** 私有方法 ********************************************/
    /***********************************************************************************************/

    /**
     * 修改状态校验
     *
     * @param
     */
    private void updateCheck(Long id) {
        GoodsAccountEntity goodsAccountEntity =this.getById(id);
        //if(goodsAccountEntity.getOrderState().equals(OrderHead_OrderStateEnum.AUDITED.getValue())){
        //    throw new RRException(String.format("已审核的销售订单禁止修改"));
        //}
    }
    /**
     * 审核状态校验
     *
     * @param
     */
    private void checkCheck(GoodsAccountEntity goodsAccountEntity) {
        //if(goodsAccountEntity.getOrderState().equals(OrderHead_OrderStateEnum.AUDITED.getValue())){
        //    throw new RRException(String.format("[%s] 此销售单已审核"));
        //}
    }

    /**
     * 删除状态校验
     *
     * @param ids
     */
    private void deleteCheck(Long[] ids) {
        for (Long id:ids) {
                GoodsAccountEntity goodsAccountEntity = this.getById(id);
        }
        //if(!saleOrderHeadEntity.getOrderState().equals(OrderHead_OrderStateEnum.WAITCHECK.getValue())){
        //    throw new RRException(String.format("只允许删除未审核的销售订单"));
        //}
    }

    /**
     * 新增和修改参数校验
     *
     * @param record
     */
    private void paramsCheck(GoodsAccountEntity record, Class<?> cls) {
        ValidatorUtils.validateEntity(record, cls);
    }
    /**
     * 获取查询条件
     *
     * @param
     */
    private QueryWrapper<GoodsAccountEntity> getQueryWrapper(Map<String, Object> params) {
        QueryWrapper<GoodsAccountEntity> queryWrapper=new QueryWrapper<>();
        if(!StrUtil.isBlankIfStr(params.get("accountDate"))){
            String accountDate=String.valueOf(params.get("accountDate"));
            String[] accountDateRange=accountDate.split("至");
            if(accountDateRange.length==2){
                queryWrapper.gt("account_date",DateUtils.getBeginTimeOfDate(accountDateRange[0]));
                queryWrapper.lt("account_date",DateUtils.getBeginTimeOfDate(accountDateRange[1]));
            }else{
                queryWrapper.gt("account_date",DateUtils.getBeginTimeOfDate(accountDate));
            }
        }
        if(!StrUtil.isBlankIfStr(params.get("accountMonth"))){
            queryWrapper.like("account_month",params.get("accountMonth"));
        }
        if(!StrUtil.isBlankIfStr(params.get("goodsCode"))){
            queryWrapper.like("goods_code",params.get("goodsCode"));
        }
        if(!StrUtil.isBlankIfStr(params.get("goodsName"))){
            queryWrapper.like("goods_name",params.get("goodsName"));
        }
        if(!StrUtil.isEmptyIfStr(params.get("propKey"))){
            queryWrapper.and(wrapper -> wrapper
            );
        }

        queryWrapper.orderByAsc("id");
        return queryWrapper;
    }
}
